﻿using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using WpfApp1.config;
using System.Configuration;

namespace WindowChromeBrowser
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        bool _isNavigating = false;
        public MainWindow()
        {
            InitializeComponent();
            InitializeAsync();
            
        }
       

       

        async void InitializeAsync()
        {
            //获取首页地址,并赋值给webview
            var Html_Uri = ConfigurationManager.AppSettings["Html_Uri"];
            webView.Source =new Uri(Html_Uri) ;
            await webView.EnsureCoreWebView2Async(null);
            webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;

            await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
            await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
            webView.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;

            webView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
            //资源拦截触发WebResourceRequested，获取到内容

            webView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;

            //拦截所有资源内容，仅当存在资源的活动筛选器并且该筛选器匹配时，才会激发WebResource请求事件。您可以使用以下命令添加一个筛选器来拦截所有请求
            webView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
            webView.CoreWebView2.SourceChanged += CoreWebView2_SourceChanged;
            //加载首页

        }
        async void GoToPageCmdExecuted(object target, ExecutedRoutedEventArgs e)
        {
            await webView.EnsureCoreWebView2Async();
            if(e.Parameter.ToString().Length >0)
            {

                if (e.Parameter.ToString().Contains("https://") || e.Parameter.ToString().Contains("http://"))
                {
                    webView.CoreWebView2.Navigate((string)e.Parameter);
                }
                else
                {
                    webView.CoreWebView2.Navigate("https://" + (string)e.Parameter);
                }
            }


        }
        //地址改变处理事件
        private void CoreWebView2_SourceChanged(object? sender, CoreWebView2SourceChangedEventArgs e)
        {
            Download_list.Items.Clear();
        }

        //对应WebResourceRequested的事件执行方法
        private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
        {

            M3u8_Down m3U8_Down = new M3u8_Down();
            MenuItem menuItem = new MenuItem();
            string url = e.Request.Uri.ToString();
            System.Diagnostics.Debug.WriteLine(url);

            Title_html.Text = webView.CoreWebView2.DocumentTitle.ToString();

            if (url.ToLower().Contains("m3u8"))
            {
                if (url.ToLower().Contains("url="))
                {
                    var uri_data = url.Split("url=")[1];
                    menuItem.Header = webView.CoreWebView2.DocumentTitle.ToString().Replace(",", "").Replace(" ", "").Replace("\t", "").Replace("\r", "").Replace("\n", "").Replace("《", "").Replace("》", "").Replace("-", "").Replace("_", "").Replace("·", "") + ";" + uri_data;//.Substring(0, 10);
                    menuItem.Click += m3U8_Down.startddd;
                    Download_list.Items.Add(menuItem);
                }
                else
                {
                    menuItem.Header = webView.CoreWebView2.DocumentTitle.ToString().Replace(",", "").Replace(" ", "").Replace("\t", "").Replace("\r", "").Replace("\n", "").Replace("《", "").Replace("》", "").Replace("-", "").Replace("_", "").Replace("·", "") + ";" + url;//.Substring(0, 10);
                    menuItem.Click += m3U8_Down.startddd;
                    Download_list.Items.Add(menuItem);
                }
            }

        }
        //网页加载完成后执行的方法
        private void CoreWebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {


        }
        void GoToPageCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = webView != null && !_isNavigating;
        }

        void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
        {
            String uri = args.TryGetWebMessageAsString();
            url.Text = uri;
        }
        //禁止webview弹出新窗口
        private void CoreWebView2_NewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            //e.NewWindow = webView22.CoreWebView2;
            //在第二个webview2上面打开这个新窗口
            webView.Source = new Uri(e.Uri.ToString());
            e.Handled = true;//禁止弹窗
        }

        private void button_MiniSize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void button_MaxSize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState= WindowState.Maximized;
            button_MaxSize.Visibility = Visibility.Collapsed;
            button_ResSize.Visibility = Visibility.Visible;
        }

        private void button_ResSize_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Normal;
            button_ResSize.Visibility = Visibility.Collapsed;
            button_MaxSize.Visibility = Visibility.Visible;
        }

        private void btn_Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void GoBack_button(object sender, RoutedEventArgs e)
        {

            webView.CoreWebView2.GoBack();
        }

        private void GoForward_button(object sender, RoutedEventArgs e)
        {

            webView.CoreWebView2.GoForward();
        }

        private void Setings_button(object sender, RoutedEventArgs e)
        {

            WindowChromeBrowser.Settings settings = new Settings();
            settings.ShowDialog();


        }
    }

    /// <summary>
    /// 读取系统主显示器，和窗体可用工作区，获得WPF可用的外边距。
    /// </summary>
    public class SystemWorkAreaToMarginConverter : IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
      {
            return new Thickness(
         //   SystemParameters.WorkArea.Left
         //, SystemParameters.WorkArea.Top
         8,
         8,
         8 , 
         SystemParameters.PrimaryScreenHeight - SystemParameters.WorkArea.Height +5
         );
     }
 
     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {
       throw new NotImplementedException();
     }
   }
}
